<template>
    <m-hot-search></m-hot-search>
    <m-grid :data="hotbrand">
        <template v-slot="{ item }">
            <image class="m-brand-img" :src="item.imageUrl" mode="scaleToFill" />
        </template>
    </m-grid>
    <indexed-list :options="brandlist" @click="bindClick" :top="top" v-if="loadLndexlist" />
</template>

<script setup lang="ts">
import { ref, shallowRef } from 'vue'
import MHotSearch from '@/components/business/MHotSearch.vue'
import { getBrandList, getHotBrand } from '@/api/product'
import pinyin from 'pinyin'
import IndexedList from '@/components/common/MIndexedList.vue'
import { onReady } from '@dcloudio/uni-app'
import MGrid from '@/components/common/MGrid.vue'
import Util from '@/util/Util'
interface indexList {
    letter: string
    data: string[]
}
let nameIdMap: Map<string, number> = new Map()
let map: Map<string, indexList> = new Map()
const brandlist = shallowRef<indexList[]>()
const hotbrand = shallowRef<Brand[][]>([])
const top = ref(0)
const loadLndexlist = ref(false)
Promise.all([getBrandList(), getHotBrand()]).then((resp) => {
    let brandlistData = resp[0]
    let brands: Brand[] = brandlistData.data || []
    brands.map((v) => {
        nameIdMap.set(v.name, v.id)
        let key = pinyin(v.name.charAt(0), {
            style: pinyin.STYLE_FIRST_LETTER,
            compact: false
        })[0][0].toUpperCase()
        let brandarr = map.get(key)
        if (brandarr) {
            brandarr.data.push(v.name)
        } else {
            map.set(key, { letter: key, data: [v.name] })
        }
    })
    brandlist.value = Array.from(map.values()).sort((a1, a2) => a1.letter.charCodeAt(0) - a2.letter.charCodeAt(0))
    hotbrand.value = Util.splitArray(resp[1].data || [], 3)
    setTimeout(() => {
        let query = uni.createSelectorQuery()
        // 选择节点
        query
            .select('.m-grid')
            .boundingClientRect((data) => {
                if (data) {
                    top.value = top.value + (data instanceof Array ? data[0].height ?? 0 : data.height ?? 0)
                }
            })
            .select('.m-search-bar')
            .boundingClientRect((data) => {
                if (data) {
                    top.value = top.value + (data instanceof Array ? data[0].height ?? 0 : data.height ?? 0)
                }
            })
            .exec()
        loadLndexlist.value = true
    })
})
function bindClick() {}
</script>

<style lang="scss" scoped>
.m-brand-img {
    width: 200rpx;
    height: 100rpx;
}
</style>
